package org.jflame.auth.authc;

import org.jflame.commons.model.BaseResult;

import java.security.GeneralSecurityException;

/**
 * 身份认证异常
 * 
 * @author yucan.zhang
 */
public class AuthcException extends GeneralSecurityException {

    private static final long serialVersionUID = 8128513200524494718L;
    private int errorCode;

    public AuthcException(String message) {
        super(message);
    }

    public AuthcException(Throwable cause) {
        super(cause);
    }

    public AuthcException(int errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }

    public AuthcException(AuthcError error) {
        super(error.msg);
        errorCode = error.getStatus();
    }

    public int getErrorCode() {
        return errorCode;
    }

    /**
     * 判断异常代指的错误是否与认证错误枚举相同
     * 
     * @see AuthcError
     * @param error
     * @return
     */
    public boolean isError(AuthcError error) {
        return error == null ? false : error.equalStatus(errorCode);
    }

    /**
     * 常见身份认证错误枚举
     * 
     * @author charles.zhang
     */
    public enum AuthcError implements BaseResult {

        AccountNotFound(1000, "账号不存在"),
        AccountExpired(1004, "账号已过期"),
        AccountLocked(1001, "账号已被锁定"),
        AccountDisabled(1002, "账号已禁用"),
        Credential(1005, "用户名或密码不正确"),
        CredentialExpired(1006, "密码已过期"),
        MaximumSessionExceeded(1010, "相同账号登录数量超过限制");

        private int status;
        private String msg;

        private AuthcError(int code, String msg) {
            this.status = code;
            this.msg = msg;
        }

        @Override
        public int getStatus() {
            return status;
        }

        @Override
        public String getMessage() {
            return msg;
        }

        public boolean equalStatus(int status) {
            return this.status == status;
        }

    }
}
